import React, { forwardRef, useState, useImperativeHandle } from 'react';
import { Modal, Input, Button } from 'antd';
import FilterGroup from './filter/FilterGroup';
import { clone as cloneDeep } from 'ramda';
import useFlowStore from '../hooks/flowStore';
import { createStyles } from 'antd-style';

const ConditionFilterModal = (_, ref) => {
  const [visible, setVisible] = useState(false);
  const [condition, setCondition] = useState(getDefault());
  const [openParams, setOpenParams] = useState(null);
  const flowContext = useFlowStore();
  const { styles } = useStyles()
  useImperativeHandle(ref, () => ({
    open: open,
  }));

  function getDefault() {
    return {
      conditionName: '',
      conditionType: 'CUSTOM',
      expression: '',
      outgoing: '',
      conditionExpressions: [],
    };
  }

  const open = (params) => {
    setOpenParams(params);
    if (typeof params.index === 'number') {
      setCondition(cloneDeep(params.data.conditions[params.index]));
    } else {
      setCondition(getDefault());
    }
    setVisible(true);
  };

  const onChange = (value) => {
    setCondition({
      ...condition,
      conditionExpressions: value,
    });
  };

  const onCancel = () => {
    setVisible(false);
  };

  const onSubmit = () => {
    setVisible(false);
    if (typeof openParams?.afterEdit === 'function') {
      openParams.afterEdit(cloneDeep(condition));
    }
  };

  const sourceList = flowContext.data.flowVariables.filter(
    (item) => item.envType === 1 || item.envType === 3
  );

  return (
    <Modal
      title="设置分支条件"
      width={640}
      open={visible}
      className={styles + " condition-filter-modal"}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={onSubmit}>
          确定
        </Button>,
      ]}
    >
      <div className="condition-name-label">分支名称</div>
      <Input
        value={condition.conditionName}
        onChange={(e) =>
          setCondition({ ...condition, conditionName: e.target.value })
        }
        className="condition-name-input"
        placeholder="请输入"
      />
      <FilterGroup
        value={condition.conditionExpressions}
        onChange={onChange}
        sourceList={sourceList}
        targetList={sourceList}
      />
    </Modal>
  );
};

const useStyles = createStyles(({ token, css }) => {
  return css`
     .el-dialog__body {
    padding-top: 10px;
  }
  .condition-name-label {
    margin-bottom: 10px;
  }
  .condition-name-input {
    margin-bottom: 10px;
  }
  `
})


export default forwardRef(ConditionFilterModal); 